<script lang="ts" setup>
import { ElMessage } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { createDropshippingTask } from "/@/api/task";
// import { getCargoList } from "/@/api/warehousing";
import type { UploadProps, UploadUserFile } from "element-plus";
import useUploadUrl from "/@/hooks/useUploadUrl";
// import { getProductList } from "/@/api/productInfo";
import axios from "axios";
import { getToken } from "/@/utils/auth";

type Props = {
  modelValue: boolean;
  isAdmin: boolean;
  userList: any;
  cargoList: any;
  productList: any;
};
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  isAdmin: false,
  userList: () => [],
  cargoList: () => [],
  productList: () => []
});

const emit = defineEmits(["update:modelValue", "submit-success"]);
const inputHandle = val => {
  emit("update:modelValue", val);
};

const inputWidth = "250px";
const formData = reactive({
  user_name: "", //	String客户名称，如果是仓库方，需要填写
  user_nid: "", // String	客户nid，如果是仓库方，需要填写
  type: null, // 	Number	类型 1-按箱发货，2-按产品发货
  amount_in_a_box: null,
  box_no: "", // String	箱麦
  checkin_identifier: "", // String	编号，可通过 /v1/get_cargo_list 获取
  product_id: null, // Number	产品id
  product_name: "", // String	产品名称
  quantity: null, // Number	数量
  file: "", // String	贴标文件地址
  notes: "" //String	备注
});
const imageUrl = ref("");
// const cargoList = ref([]);
// const productList = ref([]);
const boxInfoList = ref([]);
const maxNumber = ref(0);
const selectBoxInfoIdx = ref("");
const fileList = ref<UploadUserFile[]>([]);
const showLoading = ref(false);

// onMounted(() => {
//   getCargoList().then(({ data }) => {
//     cargoList.value = data;
//   });
//   getProductList().then(({ data }) => {
//     productList.value = data;
//   });
// });

const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  formData.file = response.data;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const initForm = () => {
  (formData.user_name = ""), //	String客户名称，如果是仓库方，需要填写
    (formData.user_nid = ""), // String	客户nid，如果是仓库方，需要填写
    (formData.type = null), // String	类型 1-按箱发货，2-按产品发货
    (formData.amount_in_a_box = null),
    (formData.box_no = ""), // String	箱麦
    (formData.checkin_identifier = ""), // String	编号，可通过 /v1/get_cargo_list 获取
    (formData.product_id = null), // Number	产品id
    (formData.product_name = ""), // String	产品名称
    (formData.quantity = null), // Number	数量
    (formData.file = ""), // String	贴标文件地址
    (formData.notes = ""); //String	备注
  if (props.isAdmin) {
    formData.user_name = "";
    formData.user_nid = "";
  }
  inputHandle(false);
};

const submit = () => {
  if (!fileList.value.length) {
    return ElMessage({
      type: "warning",
      message: "请上传文件"
    });
  } else {
    const obj = { ...formData };
    if (!props.isAdmin) {
      delete obj.user_name;
      delete obj.user_nid;
    }
    createDropshippingTask(obj).then(() => {
      ElMessage({
        type: "success",
        message: "创建成功"
      });
      initForm();
      inputHandle(false);
      emit("submit-success");
    });
  }
};

const getUserName = val => {
  formData.user_name = props.userList.find(item => item.nid === val).name;
};

const getProductName = val => {
  const { name } = props.productList.value.find(item => item.id === val);
  formData.product_name = name;
};

const selectCargo = identifier => {
  boxInfoList.value = props.cargoList[identifier].box_info;
};
const selectBox = idx => {
  formData.box_no = boxInfoList.value[idx].box_no;
  maxNumber.value = boxInfoList.value[idx].quantity;
};
const upload = param => {
  showLoading.value = true;
  const fd = new FormData();
  fd.append("file", param.file);
  const url = useUploadUrl.uploadUrl;
  const tokenData = getToken();
  const headers = {
    Token: tokenData.token
  };
  axios
    .post(url, fd, { headers: headers })
    .then(response => {
      formData.file = response.data.data;
      showLoading.value = false;
    })
    .catch(_ => {
      showLoading.value = false;
      ElMessage({
        message: "文件上传失败",
        type: "error"
      });
    });
};
</script>

<template>
  <el-dialog
    :modelValue="modelValue"
    @update:modelValue="inputHandle"
    title="创建一键代发任务"
    width="40%"
  >
    <span>
      <el-form
        :inline="true"
        :model="formData"
        label-width="auto"
        label-position="left"
      >
        <template v-if="isAdmin">
          <el-form-item label="客户名称:">
            <el-select
              v-model="formData.user_nid"
              :style="{ width: inputWidth }"
              placeholder="请选择"
              @change="getUserName"
            >
              <el-option
                v-for="item in userList"
                :key="item.nid"
                :label="item.name"
                :value="item.nid"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="类型:">
          <el-select
            v-model="formData.type"
            placeholder="请选择"
            :style="{ width: inputWidth }"
          >
            <el-option label="按箱发货" value="1" />
            <el-option label="按间发货" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="一箱多少件:" v-if="formData.type === 2">
          <el-input-number
            v-model="formData.amount_in_a_box"
            :step="1"
            :min="0"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="编号:">
          <el-select
            v-model="formData.checkin_identifier"
            placeholder="请选择"
            :style="{ width: inputWidth }"
            @change="selectCargo"
          >
            <el-option
              v-for="item in cargoList"
              :key="item.identifier"
              :label="item.identifier"
              :value="item.identifier"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="箱麦:">
          <!-- <el-input v-model="formData.box_no" :style="{ width: inputWidth }" /> -->
          <el-select
            v-model="selectBoxInfoIdx"
            placeholder="请选择"
            :style="{ width: inputWidth }"
            @change="selectBox"
          >
            <el-option
              v-for="(item, index) in boxInfoList"
              :key="index"
              :label="item.box_no"
              :value="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品id:">
          <el-select
            v-model="formData.product_id"
            placeholder="请选择"
            :style="{ width: inputWidth }"
            @change="getProductName"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量:">
          <el-input-number
            v-model="formData.quantity"
            :step="1"
            :min="0"
            :max="maxNumber"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="formData.notes" :style="{ width: inputWidth }" />
        </el-form-item>
        <el-form-item label="面单文件:" class="picture-form-item">
          <el-upload
            class="upload-demo"
            action=""
            :headers="useUploadUrl.headers"
            :on-success="handleAvatarSuccess"
            :http-request="upload"
            v-model:file-list="fileList"
            limit="1"
          >
            <el-button type="primary" :loading="showLoading"
              >上传文件</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="initForm">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.picture-form-item) {
  vertical-align: top !important;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  width: 150px;
  height: 150px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
